<?php
/*电子价格牌绑定模块*/
namespace SDXApi\Controller;
use Think\Controller;
use Think\Model;
class TagController extends AppController {
	public $pagesize=10;

	public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '',$check_sign=true)
	{
		parent::_initialize($apptoken, $apptime, $check_uid, $session_id,false);
	}
	
    /*TODO 插入到配送订单列表中*/
    public function get_config(){
// 		$config=array(
// 			'url'=>'http://120.24.217.223:8080/mck-server',
// 			'routers'=>array(
// 				'1295003697'
// 			)
// 		);
		$url=$this->get_url_config();
		$routes=$this->get_routes_config();
		$config=array(
			'url'=>$url,
			'routers'=>$routes
		);
		returnApiSuccess($config,'success');
    }
    
    
    
    /**
     * 绑定价格牌
     */
    public  function bind_tag(){
    	if(!isset($_REQUEST['goods_id'])&&!isset($_REQUEST['goods_sn'])){
    		returnApiError('请输入商品ID或者商品条码！');
    	}else{
    		if(!isset($_REQUEST['tag_id'])){
    			returnApiError('请输入价格牌编号！');
    		}else{
    			$Model=new Model();
    			$goods_id=0;
    			if(!isset($_REQUEST['goods_id'])){
    				$sql='select goods_id from '.C('DB_PREFIX')."goods where goods_sn='".$_REQUEST['goods_sn']."' and is_delete = 0 limit 1";
    				$row=$Model->query($sql);
    				if($row){
    					$goods_id=$row[0]['goods_id'];
    					$_REQUEST['goods_id']=$goods_id;   	
    					//绑定
    					$this->bind_tag_price();    
    				}else{
    					returnApiError('输入的条码找不到对应的产品信息！');
    				}
    			}else{
    				//绑定
    				$this->bind_tag_price();
    			}
    		}   		
    	}
    }
    
    
    
    /**
     * 更新商品信息
     */
    public function update_goods_info(){
    	$data=$this->get_goods_info();
    	if(count($data)>0){
    		$scoket_url=$this->get_url_config();
    		$url = $scoket_url."/productsAction_addOrEdit.action";
    		$returnData=http_post($url,$data);
    		if($returnData==""){
    			//写商品信息操作日志
    			$this->write_goods_info($data);
    			
    			
    			returnApiSuccess(array(),'更新/添加商品信息成功');
    		}else {
    			returnApiError('更新/添加商品信息失败！');
    		}
    	}else{
    		returnApiError('获取商品信息失败！');
    	}
    }
    
    
    
    private function bind_tag_price(){
    	//获取商品信息
    	$data=$this->get_goods_info();
    	if(count($data)>0){
    		$scoket_url=$this->get_url_config();
    		$url = $scoket_url."/productsAction_addOrEdit.action";
    		$Data=http_post($url,$data);
    		//echo json_encode($Data);
    		if($Data==""){
    			//写商品信息操作日志
    			$this->write_goods_info($data);
    			
    			//绑定价格牌
    			$gateway_id=$this->get_route_config();//路由器ID
    			$requestData=array(
    					"tag_id"=>$_REQUEST['tag_id'],
    					"products.barcode"=>$data['barcode'],
    					"gateway.id"=>$gateway_id,
    			);
    			$requestUrl=$scoket_url."/tagAction_bindings.action";
    			//请求接口
    			$responseData=http_post($requestUrl,$requestData);
    			if($responseData){
    				$returnData=array();
    				switch ($responseData){
    					case '10000':
    						$returnData=array('result'=>'10000','remark'=>'绑定成功');
    						break;
    				case '10001':
    						$returnData=array('result'=>'10001','remark'=>'商品/路由器 不存在');
    						break;
    				case '10002':
    						$returnData=array('result'=>'10002','remark'=>'重复');
    						break;
    				case '10003':
    						$returnData=array('result'=>'10003','remark'=>'失败');
    						break;
    				}
    				//写绑定日志记录
    				$this->write_bind_info($data,$requestData);
    				
    				returnApiSuccess($returnData,'绑定信息成功！');
    			}else {
    				returnApiError('绑定价格牌失败！');
    			}
    		}else {
    			returnApiError('更新/添加商品信息失败！');
    		}
    	}else{
    		returnApiError('获取商品信息失败！');
    	}
    }
    
    
    
    
    /**
     * 获取商品信息
     */
    private function get_goods_info(){
    	if(isset($_REQUEST['goods_id'])){
    		$goods_id=$_REQUEST['goods_id'];
    		if(intval($goods_id)){
    			$time = gmtime();
    			$sql = 'SELECT g.*, c.measure_unit, b.brand_id, b.brand_name AS goods_brand, m.type_money AS bonus_money, ' .
    					'FORMAT(IFNULL(mp.user_price, g.shop_price),2) AS vip_price, ' .
    					"(SELECT IFNULL(SUM(practical_num),0) FROM " . C('DB_PREFIX') . "goods_storage WHERE goods_id=g.goods_id) AS inventory " .
    					'FROM ' . C('DB_PREFIX') . 'goods AS g ' .
    					'LEFT JOIN ' .C('DB_PREFIX'). 'category AS c ON g.cat_id = c.cat_id ' .
    					'LEFT JOIN ' . C('DB_PREFIX') . 'brand AS b ON g.brand_id = b.brand_id ' .
    					'LEFT JOIN ' .C('DB_PREFIX') . 'bonus_type AS m ' .
    					"ON g.bonus_type_id = m.type_id AND m.send_start_date <= '$time' AND m.send_end_date >= '$time'" .
    					" LEFT JOIN " .C('DB_PREFIX'). "member_price AS mp " .
    					"ON mp.goods_id = g.goods_id AND mp.user_rank =2 " .
    					"WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " .
    					"GROUP BY g.goods_id";
    			$Model=new Model();
    			$data=$Model->query($sql);
    			if($data){
    				$item=$data[0];
    				if (empty($item['ycd']))
                        $item['ycd'] = $res[0]['origin'];
    				if (empty($item['wjy']))
    					$item['wjy'] = '杨宝元';

					$goodsPriceInfo=array(
						'id' => $item['goods_sn'],
						'goods_id' => $item['goods_id'],
						'name' => $item['goods_name'],
						'brands' => $item['goods_brand'],
						'barcode' => $item['goods_sn'],
						'standard' => $item['gg'] ? $item['gg'] : '',
						'unit' => $item['dw'] ? $item['dw'] : '',
						'price' => $item['shop_price'] ? $item['shop_price'] : '',
						'memberPrice' => $item['vip_price'] ? $item['vip_price'] : '',
						'origin' => $item['ycd'] ? $item['ycd'] :'',
						'twoBarCodes' => 'https://w.shidexian.com/?index=!/info?id=' . $item['goods_id'],
						'priceController' => $item['wjy'],
						'inventory' => $item['inventory']
					);

					if($item['is_promote']==1){
						$goodsPriceInfo['salePrice']=$item['promote_price'];
						$goodsPriceInfo['sales']="促销期：".local_date("m.d",$item['promote_start_date'])."~".local_date("m.d",$item['promote_end_date']);
					}
    				return $goodsPriceInfo;
    			}else{
    				return array();
    			}
    		}else{
    			return array();
    		}
    	}else{
    		return array();
    	}
    }
    
    
    private function write_goods_info($goodsinfo){
    	$Model=new Model();
    	$operator="";
    	if(isset($_REQUEST['user_id'])){
    		$operator=$_REQUEST['user_id'];
    	}
    	$time=date('y-m-d h:i:s',time());
    	//插入日志记录
    	$sql="insert into sdx_tag_goodsinfo_log(goods_id
    			,goods_sn
    			,goods_name
    			,goods_price
    			,goods_VIPPrice
    			,goods_unit
    			,goods_standard
    			,goods_origin
    			,twoBarCodes
    			,priceController
    			,inventory
    			,createtime
    			,creator)
    			values(".$goodsinfo['goods_id'].",'".$goodsinfo['barcode']."','".$goodsinfo['name']."','".$goodsinfo['price']."'
    					,'".$goodsinfo['memberPrice']."','".$goodsinfo['unit']."','".$goodsinfo['standard']."'
    					,'".$goodsinfo['origin']."','".$goodsinfo['twoBarCodes']."'
    					,'".$goodsinfo['priceController']."','".$goodsinfo['inventory']."','".$time."','".$operator."')";
    	$Model->execute($sql);
    	//$Model->query($sql);
    	//查询最新的商品记录
    	$sql="select goods_id,goods_sn from sdx_tag_goodsinfo where goods_id=".$goodsinfo['goods_id']."  limit 1";
    	$row=$Model->query($sql);
    	if($row){
    		//有记录则更新
    		$sql="update sdx_tag_goodsinfo set 
    				goods_sn='".$goodsinfo['barcode']."',goods_name='".$goodsinfo['name']."',goods_price='".$goodsinfo['price']."'
    				,goods_VIPPrice='".$goodsinfo['memberPrice']."',goods_unit='".$goodsinfo['unit']."',goods_standard='".$goodsinfo['standard']."'
    				,goods_origin='".$goodsinfo['origin']."',twoBarCodes='".$goodsinfo['twoBarCodes']."',priceController='".$goodsinfo['priceController']."'
    				,inventory='".$goodsinfo['inventory']."',lasttime='".$time."',lastoperator='".$operator."'  where goods_id=".$goodsinfo['goods_id'];
    	}else{
    		//没记录则插入记录
    		$sql="insert into sdx_tag_goodsinfo(goods_id
    			,goods_sn
    			,goods_name
    			,goods_price
    			,goods_VIPPrice
    			,goods_unit
    			,goods_standard
    			,goods_origin
    			,twoBarCodes
    			,priceController
    			,inventory
    			,createtime
    			,creator,lasttime,lastoperator)
    			values(".$goodsinfo['goods_id'].",'".$goodsinfo['barcode']."','".$goodsinfo['name']."','".$goodsinfo['price']."'
    					,'".$goodsinfo['memberPrice']."','".$goodsinfo['unit']."','".$goodsinfo['standard']."'
    					,'".$goodsinfo['origin']."','".$goodsinfo['twoBarCodes']."'
    					,'".$goodsinfo['priceController']."','".$goodsinfo['inventory']."','".$time."','".$operator."','".$time."','".$operator."')";
    	}
    	$Model->execute($sql);
    	//$Model->query($sql);
    }
    
    
    
    /**
     * 插入绑定价格牌记录
     * @param unknown $goodsinfo
     * @param unknown $bindinfo
     */
    private function  write_bind_info($goodsinfo,$bindinfo){
    	$Model=new Model();
    	$operator="";
    	if(isset($_REQUEST['user_id'])){
    		$operator=$_REQUEST['user_id'];
    	}
    	$time=date('y-m-d h:i:s',time());
    	//插入日志记录
    	$sql="insert into sdx_tag_bind_log(
    			tag_id
    			,gateway_id
    			,goods_id
    			,goods_sn
    			,goods_name
    			,goods_price
    			,goods_VIPPrice
    			,goods_unit
    			,goods_standard
    			,goods_origin
    			,twoBarCodes
    			,priceController
    			,inventory
    			,createtime
    			,creator)
    			values('".$bindinfo["tag_id"]."','".$bindinfo["gateway.id"]."',".$goodsinfo['goods_id'].",'".$goodsinfo['barcode']."','".$goodsinfo['name']."','".$goodsinfo['price']."'
    					,'".$goodsinfo['memberPrice']."','".$goodsinfo['unit']."','".$goodsinfo['standard']."'
    					,'".$goodsinfo['origin']."','".$goodsinfo['twoBarCodes']."'
    					,'".$goodsinfo['priceController']."','".$goodsinfo['inventory']."','".$time."','".$operator."')";
    	$Model->execute($sql);
    	//$Model->query($sql);
    	//查询最新的商品记录
    	$sql="select tag_id,goods_id from sdx_tag_bind where tag_id='".$bindinfo["tag_id"]."'  limit 1";
    	$row=$Model->query($sql);
    	if($row){
    		//有记录则更新
    		$sql="update sdx_tag_bind set 
    				gateway_id='".$bindinfo["gateway.id"]."',goods_id=".$goodsinfo['goods_id']."
    				,goods_sn='".$goodsinfo['barcode']."',goods_name='".$goodsinfo['name']."',goods_price='".$goodsinfo['price']."'
    				,goods_VIPPrice='".$goodsinfo['memberPrice']."',goods_unit='".$goodsinfo['unit']."',goods_standard='".$goodsinfo['standard']."'
    				,goods_origin='".$goodsinfo['origin']."',twoBarCodes='".$goodsinfo['twoBarCodes']."',priceController='".$goodsinfo['priceController']."'
    				,inventory='".$goodsinfo['inventory']."',lasttime='".$time."',lastoperator='".$operator."'  where tag_id='".$bindinfo["tag_id"]."'";
    	}else{
    		//没记录则插入记录
    		$sql="insert into sdx_tag_bind(
    			tag_id
    			,gateway_id
    			,goods_id
    			,goods_sn
    			,goods_name
    			,goods_price
    			,goods_VIPPrice
    			,goods_unit
    			,goods_standard
    			,goods_origin
    			,twoBarCodes
    			,priceController
    			,inventory
    			,createtime
    			,creator,lasttime,lastoperator)
    			values('".$bindinfo["tag_id"]."','".$bindinfo["gateway.id"]."',".$goodsinfo['goods_id'].",'".$goodsinfo['barcode']."','".$goodsinfo['name']."','".$goodsinfo['price']."'
    					,'".$goodsinfo['memberPrice']."','".$goodsinfo['unit']."','".$goodsinfo['standard']."'
    					,'".$goodsinfo['origin']."','".$goodsinfo['twoBarCodes']."'
    					,'".$goodsinfo['priceController']."','".$goodsinfo['inventory']."','".$time."','".$operator."','".$time."','".$operator."')";
    	}
    	$Model->execute($sql);
    	//$Model->query($sql);
    	
    }
    
    
    
    
    /**
     * 获取请求接口的地址
     * @return string
     */
    private  function get_url_config(){
    	return 'http://120.24.217.223:8080/mck-server';
    }
    
    
    /**
     * 获取路由器ID
     * @return string
     */
    private function get_route_config(){
    	return '1295003697';
    }
    
    /**
     * 获取路由器
     * @return string[]
     */
    private function get_routes_config(){
    	return array('1295003697');
    }
    
    public  function bind_tag_test(){
    	if(!isset($_REQUEST['goods_id'])&&!isset($_REQUEST['goods_sn'])){
    		returnApiError('请输入商品ID或者商品条码！');
    	}else{
    		if(!isset($_REQUEST['tag_id'])){
    			returnApiError('请输入价格牌编号！');
    		}else{
    			$Model=new Model();
    			$goods_id=0;
    			if(!isset($_REQUEST['goods_id'])){
    				$sql='select goods_id from '.C('DB_PREFIX')."goods where goods_sn='".$_REQUEST['goods_sn']."' and is_delete = 0 limit 1";
    				$row=$Model->query($sql);
    				if($row){
    					$goods_id=$row[0]['goods_id'];
    					$_REQUEST['goods_id']=$goods_id;
    					//绑定
    					$this->test_bind_tag();
    				}else{
    					returnApiError('输入的条码找不到对应的产品信息！');
    				}
    			}else{
    				//绑定
    				$this->test_bind_tag();
    			}
    		}
    	}
    }
    
    
    
    private function test_bind_tag(){
    	//获取商品信息
    	$data=$this->get_goods_info();
    	if(count($data)>0){
    		//绑定价格牌
    		$gateway_id='1295003697';//路由器ID暂时写死
    		$requestData=array(
    					"tag_id"=>$_REQUEST['tag_id'],
    					"products.barcode"=>$data['barcode'],
    					"gateway.id"=>$gateway_id,
    		);
    		//写商品信息日志记录
    		$this->write_goods_info($data);
    		//写绑定日志记录
    		$this->write_bind_info($data,$requestData); 
    		$responseData=$_REQUEST['result'];
    		$returnData=array();
    		switch ($responseData){
    			case '10000':
    				$returnData=array('result'=>'10000','remark'=>'绑定成功');
    				break;
    			case '10001':
    				$returnData=array('result'=>'10001','remark'=>'商品/路由器 不存在');
    				break;
    			case '10002':
    				$returnData=array('result'=>'10002','remark'=>'重复');
    				break;
    			case '10003':
    				$returnData=array('result'=>'10003','remark'=>'失败');
    				break;
    		}
    		returnApiSuccess($returnData,'绑定信息成功！');
    		
    	}else{
    		returnApiError('获取商品信息失败！');
    	}
    }
    
    
    
    
    
    
}